package org.example.booklist.service;


import org.example.booklist.dao.BookDao;
import org.example.booklist.enums.BookStatus;
import org.example.booklist.mapper.BookMapper;
import org.example.booklist.model.BookInfo;
import org.example.booklist.model.PageRequest;
import org.example.booklist.model.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Service
public class BookService {

    @Autowired
    private BookMapper bookMapper;

    public List<BookInfo> getBookList(){
        BookDao bookDao = new BookDao();
        List<BookInfo> bookInfos = bookDao.mockData();
        for(BookInfo bookInfo : bookInfos){
            if(bookInfo.getStatus() == 2){
                bookInfo.setStatusCN("不可借阅");
            }else{
                bookInfo.setStatusCN("可借阅");
            }
        }
        return bookInfos;
    }

    @Transactional // 添加事务注解
    public Integer insertBook(BookInfo bookInfo) {
        return bookMapper.insertBook(bookInfo);
    }

    public PageResult<BookInfo> getBookListPage(PageRequest pageRequest) {
        // 获取总记录数
        Integer count = bookMapper.count();

        // 获取当前页的数据
        List<BookInfo> bookInfos = bookMapper.queryBookPage(pageRequest.getOffset(), pageRequest.getPageSize());

        //处理状态statusCN：
        for(BookInfo bookInfo: bookInfos){
           bookInfo.setStatusCN(BookStatus.getDescByCode(bookInfo.getStatus()).getDesc());
        }


        // 使用泛型创建PageResult
        return new PageResult<BookInfo>(bookInfos, count,pageRequest);
    }


   //根据ID查询图书信息：
    public BookInfo queryBookById(Integer bookId){
        BookInfo bookInfo = bookMapper.queryBookById(bookId);
        bookInfo.setStatusCN(BookStatus.getDescByCode(bookInfo.getStatus()).getDesc());
        return bookInfo;
    }

    public Integer updateBookById(BookInfo bookInfo) {

        return bookMapper.updateBookById(bookInfo);
    }

    public Integer batchDeleteBookByIds(List<Integer> ids) {
        return bookMapper.batchDeleteBookByIds(ids);
    }
}
